import { defineStore } from 'pinia'
// import userApi from "@/api/user";
import { default as userApi } from '@/api/user'
import type { LoginParamsData, UserInfoData } from '@/api/user'

interface UserInfoStateData {
  token: string
  userInfo: UserInfoData
}

export const useUserInfoStore = defineStore('userInfo', {
  state(): UserInfoStateData {
    return {
      // token:'',
      token: localStorage.getItem('token_key') || '',
      userInfo: {
        routes: [],
        buttons: [],
        roles: [],
        name: '',
        avatar: '',
      },
    }
  },
  actions: {
    async login(loginParams: LoginParamsData) {
      try {
        const result = await userApi.userLogin(loginParams)
        this.token = result.token
        localStorage.setItem('token_key', result.token)
        return 'ok'
      } catch (error) {
        return Promise.reject('登录失败')
      }
    },
    //获取用户信息的逻辑
    async getUserInfo() {
      try {
        const result = await userApi.getUserInfo()
        this.userInfo = result
        return 'ok'
      } catch (error) {
        return Promise.reject('获取用户信息失败')
      }
    },
    //需要重置一些状态和数据时，调用该函数可以将相关状态和数据恢复到初始状态。
    reset() {
      this.token = ''
      localStorage.removeItem('token_key')
      this.userInfo = {
        routes: [],
        buttons: [],
        roles: [],
        name: '',
        avatar: '',
      }
    },
    //退出登录的逻辑
    async logout() {
      try {
        await userApi.userLogout();
        this.reset();
        return 'ok';
      } catch (error) {
        return Promise.reject('退出登录失败')
      }
    },
  },
  getters: {},
})
